<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Form Validation</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="how-to-create-a-struts-2-web-application.html">How To Create A Struts 2 Web Application</a>&nbsp;&gt;&nbsp;<a href="create-struts-2-web-application-with-artifacts-in-web-inf-lib-and-use-ant-to-build-the-application.html">Create Struts 2 Web Application With Artifacts In WEB-INF lib and Use Ant To Build The Application</a>&nbsp;&gt;&nbsp;<a href="hello-world-using-struts-2.html">Hello World Using Struts 2</a>&nbsp;&gt;&nbsp;<a href="using-struts-2-tags.html">Using Struts 2 Tags</a>&nbsp;&gt;&nbsp;<a href="coding-struts-2-actions.html">Coding Struts 2 Actions</a>&nbsp;&gt;&nbsp;<a href="processing-forms.html">Processing Forms</a>&nbsp;&gt;&nbsp;<a href="form-validation.html">Form Validation</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Form Validation</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14811892">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14811892">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14811892">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14811892">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14811892">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14811892">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>This tutorial assumes you've completed the <a shape="rect" href="processing-forms.html">Processing Forms</a> tutorial and have a working form_processing project. The example code for this tutorial, form_validation, is available for checkout from the Struts 2 GitHub repository: <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a>.</p></div></div><h3 id="FormValidation-Introduction">Introduction</h3><p>In this tutorial we'll explore using Struts 2 to validate the user's input on a form. There are two ways you can use Struts 2 to do form validation. This tutorial will cover the more basic method, where the validation is included in the Struts 2 Action class.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="FormValidation-AddvalidateMethod">Add validate Method</h3><p>To enable the Struts 2 Action class to validate a user's input on a Struts 2 form, you must define a validate method in your Action class. Using the example from <a shape="rect" href="processing-forms.html">Processing Forms</a> tutorial, let's say that we have these business rules:</p><p>1. User must provide a first name<br clear="none"> 2. User must provide an email address<br clear="none"> 3. User younger then 18 cannot register</p><p>If you recall from the <a shape="rect" href="processing-forms.html">Processing Forms</a> tutorial the user's input into the form fields is placed by Struts 2 into the Java model class personBean. So a user's input into the firstName field would end up as the value for personBean's firstName instance field (via the personBean.setFirstName method).</p><p>In the validate method we can refer to get the values of personBean's instance fields by using the appropriate get methods. Once we have the values we can employ logic to enforce our business rules.</p><p>Add the following validate method to Register.java (the Action class).</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>validate method</b></div><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">	public void validate(){
		
		if ( personBean.getFirstName().length() == 0 ){	

			addFieldError( "personBean.firstName", "First name is required." );
			
		}
		
				
		if ( personBean.getEmail().length() == 0 ){	

			addFieldError( "personBean.email", "Email is required." );
			
		}
		
		if ( personBean.getAge() &lt; 18 ){	

			addFieldError( "personBean.age", "Age is required and must be 18 or older" );
			
		}
		
		
	}
</pre>
</div></div><p>When the user presses the submit button on the register form, Struts 2 will transfer the user's input to the personBean's instance fields. Then Struts 2 will automatically execute the validate method. If any of the if statements are true, Struts 2 will call its addFieldError method (which our Action class inherited by extending ActionSupport).</p><p>If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return "input" as the result of calling the action.</p><h3 id="FormValidation-HandleInputBeingReturned">Handle Input Being Returned</h3><p>So what should we do if Struts 2 returns "input" indicating that the user's input in the form is not valid? In most cases we will want to redisplay the web page that has the form and include in the form error messages to inform the user what is wrong.</p><p>To handle the return value of "input" we need to add the following result to our action node in struts.xml.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;result name="input"&gt;/register.jsp&lt;/result&gt;
</pre>
</div></div><p>The above result node goes just after the success result node for the register action and before the closing of the action node.</p><h3 id="FormValidation-ErrorMessages">Error Messages</h3><p>So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp. Since we used Struts 2 form tags, automatically Struts 2 will add the error messages. These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first is the form field name to which the error applies and the second is the error message to display above that form field.</p><p>So the following addFieldError method call:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">addFieldError( "personBean.firstName", "First name is required.")
</pre>
</div></div><p>will cause the message "First name is required" to be displayed above the firstName field on the form.</p><p>If you have made the above changes to the <a shape="rect" href="processing-forms.html">Processing Forms</a> tutorial or you have downloaded from <a shape="rect" class="external-link" href="http://code.google.com/p/struts2-examples/downloads/list" rel="nofollow">Google Code</a> either the Form_Validation_Struts2_Ant or Form_Validation_Struts2_Mvn projects run the application (see the README.txt in the project root folder). Click on the Please register link. On the registration form, just click the submit button and you should see:</p><p><span class="confluence-embedded-file-wrapper"><img class="confluence-embedded-image" src="form-validation.data/form_errors.png"></span></p><p>Struts 2 called the validate method, validation failed, the register.jsp was displayed with the error messages.</p><h3 id="FormValidation-StylingTheErrorMessages">Styling The Error Messages</h3><p>The Struts 2 s:head tag can be used to provide CSS that includes a style for the error message. Add <code>&lt;s:head /&gt;</code> to register.jsp before the closing HTML <code>&lt;/head&gt;</code> tag. Go through the same steps as above and you should see:</p><p><span class="confluence-embedded-file-wrapper"><img class="confluence-embedded-image" src="form-validation.data/form_errors_styled.png"></span></p><h3 id="FormValidation-Summary">Summary</h3><p>This tutorial covered validating a user's form input by adding a validate method to an Action class. There is another more sophisticated way to validate user input using XML. If you want to learn more about using XML for validation in Struts 2 see <a shape="rect" href="validation.html">Validation</a>.</p><h3 id="FormValidation-UpNext">Up Next</h3><p>In our next tutorial we'll cover how to use message resource files to separate out the text from the view page.</p><div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Next</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Onward to <a shape="rect" href="message-resource-files.html">Message Resource Files</a></p></td></tr><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Prev</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Return to <a shape="rect" href="processing-forms.html">Processing Forms</a></p></td></tr></tbody></table></div></div>
        </div>

                    <div class="tabletitle">
                Children
            <span class="smalltext" id="show" style="display: inline;">
              <a href="javascript:showChildren()">Show Children</a></span>
            <span class="smalltext" id="hide" style="display: none;">
              <a href="javascript:hideChildren()">Hide Children</a></span>
            </div>
            <div class="greybox" id="children" style="display: none;">
                                                    $page.link($child)
                    <span class="smalltext">(Apache Struts 2 Documentation)</span>
                    <br>
                            </div>
        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
